# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ggplot2)
library(dplyr)
library(tidyr)
library(tibble)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(ropls)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

data <- read.csv(opt$i, header = T) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    gather("SampleID", "Value", - Name) %>%
    spread(Name, "Value") %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    as.data.frame()

classNotes <- sampleInfo %>%
.$ClassNote %>%
unique()
cn <- combn(classNotes, 2)

for (i in 1 : ncol(cn)) {
    row <- cn[, i]
    group1Name <- row[1]
    group2Name <- row[2]
    eachData <- data %>%
    filter(ClassNote %in% c(group1Name, group2Name))
    x <- eachData %>%
        select(- c("ClassNote")) %>%
        column_to_rownames("SampleID")
    crossValI <- min(nrow(x),7)
    pcaRs <- opls(x, plotL = F, crossvalI = crossValI)
    parameterData <- pcaRs@modelDF %>%
        select(c(1 : 2)) %>%
        set_colnames(c("R2", "Cumulative R2")) %>%
        mutate(Name = paste0("PC", 1 : n())) %>%
        column_to_rownames("Metabolite") %>%
        t()
    parent <- paste0(group2Name, "_", group1Name)
    createWhenNoExist(parent)
    write.csv(parameterData, paste0(parent, "/PCA_", group2Name, "_", group1Name , "_Parameters.csv"), quote = FALSE)
    print(pcaRs@scoreMN)
    pcData <- pcaRs@scoreMN %>%
        as.data.frame() %>%
        rownames_to_column("SampleID")
    write.table(pcData, paste0(parent, "/PCA_", group2Name, "_", group1Name , "_data.txt"),sep = "\t",col.names = NA, quote = FALSE)
}


